/*
 * @Author: kenan
 * @Date: 2022-01-17 16:38:21
 * @LastEditors: Jason Chen
 * @LastEditTime: 2022-12-05 14:40:35
 * @Description: file content
 */
package system

import (
	"reflect"
	"strings"
	"time"

	"github.com/flipped-aurora/gin-vue-admin/server/global"

	pluginModel "github.com/flipped-aurora/gin-vue-admin/server/plugin/db/model"
)

var DbUpdate = new(db_update)

type db_update struct {
}

func (u *db_update) TableName() string {
	return ""
}

func (u *db_update) Initialize() error {
	var removeEntities, insertEntities []interface{}

	// 示例
	status := new(bool)
	*status = true

	//resource limit
	insertEntities = append(insertEntities, pluginModel.DatabaseModel{DbType: pluginModel.DbTypeEnum_Mysql, DbHost: "127.0.0.1", DbPort: 13306, DbUserName: "user", Password: "123456", InstanceName: "orcl"})
	insertEntities = append(insertEntities, pluginModel.DatabaseModel{DbType: pluginModel.DbTypeEnum_Oracel, DbHost: "127.0.0.1", DbPort: 1521, DbUserName: "user", Password: "123456", InstanceName: "orcl"})

	return removeAndInsert(removeEntities, insertEntities)
}

func removeAndInsert(removeEntities, insertEntities []interface{}) error {
	// remove
	for _, entity := range removeEntities {

		interface_ := reflect.New(reflect.TypeOf(entity)).Interface()
		db := global.GVA_DB.Where(entity)
		if db.First(interface_).RowsAffected == 0 { // 数据不存在，就退出
			continue
		}
		err := db.Delete(interface_).Error
		if err != nil {
			return err
		}
	}

	// insert
	for _, entity := range insertEntities {
		t := reflect.TypeOf(entity)
		if global.GVA_DB.Where(entity).First(reflect.New(t).Interface()).RowsAffected == 1 { // 如果数据存在就退出
			continue
		}

		v := reflect.ValueOf(entity)
		hasGVA_MODEL := false
		for k := 0; k < t.NumField(); k++ {
			columnName := t.Field(k).Name
			if strings.EqualFold(columnName, "GVA_MODEL") {
				hasGVA_MODEL = true
				continue
			}
		}

		datas := make(map[string]interface{})
		if hasGVA_MODEL {
			datas["created_at"] = time.Now()
			datas["updated_at"] = time.Now()
		}

		for k := 0; k < t.NumField(); k++ {
			columnName := t.Field(k).Name
			if strings.EqualFold(columnName, "GVA_MODEL") {
				continue
			}
			columnValue := v.Field(k).Interface()
			gormStr := t.Field(k).Tag.Get("gorm")
			for _, tmp := range strings.Split(gormStr, ";") {
				if strings.Contains(tmp, "column") {
					columnName = strings.Split(tmp, ":")[1]
					break
				}
			}
			isEmpty := false

			if v.Field(k).String() == "" {
				isEmpty = true
			} else {
				kind := v.Field(k).Kind().String()
				if strings.Contains(strings.ToLower(kind), "slice") {
					isEmpty = true
				}
			}

			if !isEmpty {
				datas[columnName] = columnValue
			}

		}

		model := reflect.New(reflect.TypeOf(entity)).Interface()
		err := global.GVA_DB.Model(model).Create(datas).Error
		if err != nil {
			return err
		}
	}

	return nil
}

func (u *db_update) CheckDataExist() bool {

	return false
}
